"""
项目管理模块路由
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List

from ..db import get_db, ParameterCategory as ParameterCategoryModel, Parameter as ParameterModel
from ..schemas import (
    Project, ProjectCreate, ProjectUpdate, ProjectList, MessageResponse, ProjectYearRangeUpdate
)
from ..db.parameters import crud
from ..db.parameters.crud import (
    create_project, get_project_by_name_en, get_projects_with_counts,
    update_project, delete_project, update_project_year_range
)

router = APIRouter(prefix="/api/projects", tags=["项目管理"])


@router.post("", response_model=Project, status_code=201)
async def create_project_endpoint(project: ProjectCreate, db: Session = Depends(get_db)):
    """创建项目"""
    # 检查项目英文名称是否已存在
    existing_project = get_project_by_name_en(db, project.name_en)
    if existing_project:
        raise HTTPException(
            status_code=400,
            detail=f"项目英文名称 '{project.name_en}' 已存在"
        )
    
    return create_project(db, project)


@router.get("", response_model=List[ProjectList])
async def get_projects_endpoint(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取项目列表"""
    projects = get_projects_with_counts(db, skip=skip, limit=limit)
    return projects


@router.get("/{project_name_en}", response_model=Project)
async def get_project_endpoint(project_name_en: str, db: Session = Depends(get_db)):
    """获取项目详情"""
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    return project


@router.put("/{project_name_en}", response_model=ProjectList)
async def update_project_endpoint(
    project_name_en: str, 
    project_update: ProjectUpdate, 
    db: Session = Depends(get_db)
):
    """更新项目"""
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    updated_project = update_project(db, project.id, project_update)
    if not updated_project:
        raise HTTPException(
            status_code=500,
            detail="更新项目失败"
        )
    
    # 获取更新后的项目统计信息
    category_count = db.query(ParameterCategoryModel).filter(ParameterCategoryModel.project_id == updated_project.id).count()
    parameter_count = db.query(ParameterModel).join(ParameterCategoryModel).filter(ParameterCategoryModel.project_id == updated_project.id).count()
    
    # 返回包含统计信息的项目数据
    return {
        "id": updated_project.id,
        "name": updated_project.name,
        "name_en": updated_project.name_en,
        "description": updated_project.description,
        "time_horizon": updated_project.time_horizon,
        "start_year": updated_project.start_year,
        "year_step": updated_project.year_step,
        "end_year": updated_project.end_year,
        "sort_order": updated_project.sort_order,
        "created_at": updated_project.created_at,
        "updated_at": updated_project.updated_at,
        "category_count": category_count,
        "parameter_count": parameter_count
    }


@router.delete("/{project_name_en}", response_model=MessageResponse)
async def delete_project_endpoint(project_name_en: str, db: Session = Depends(get_db)):
    """删除项目"""
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(
            status_code=404,
            detail=f"项目 '{project_name_en}' 不存在"
        )
    
    success = delete_project(db, project.id)
    if success:
        return MessageResponse(message=f"项目 '{project_name_en}' 删除成功")
    else:
        raise HTTPException(
            status_code=500,
            detail="删除项目失败"
        )


@router.put("/{project_name_en}/year-range", response_model=ProjectList)
async def update_project_year_range_endpoint(
    project_name_en: str,
    payload: ProjectYearRangeUpdate,
    db: Session = Depends(get_db)
):
    """更新项目年份区间，并调整所有关联年份的列表参数。"""
    project = get_project_by_name_en(db, project_name_en)
    if not project:
        raise HTTPException(status_code=404, detail=f"项目 '{project_name_en}' 不存在")

    try:
        updated_project = update_project_year_range(db, project.id, payload.start_year, payload.end_year, payload.year_step)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    if not updated_project:
        raise HTTPException(status_code=500, detail="更新年份区间失败")

    category_count = db.query(ParameterCategoryModel).filter(ParameterCategoryModel.project_id == updated_project.id).count()
    parameter_count = db.query(ParameterModel).join(ParameterCategoryModel).filter(ParameterCategoryModel.project_id == updated_project.id).count()

    return {
        "id": updated_project.id,
        "name": updated_project.name,
        "name_en": updated_project.name_en,
        "description": updated_project.description,
        "time_horizon": updated_project.time_horizon,
        "start_year": updated_project.start_year,
        "year_step": updated_project.year_step,
        "end_year": updated_project.end_year,
        "sort_order": updated_project.sort_order,
        "created_at": updated_project.created_at,
        "updated_at": updated_project.updated_at,
        "category_count": category_count,
        "parameter_count": parameter_count
    }

